#include "toolwidget.h"
#include "ui_toolwidget.h"
#include <QPainter>
#include <QBitmap>
#include <QStyleOption>
#include <QtDebug>
ToolWidget::ToolWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ToolWidget)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);// 设置窗口标志，使其表现为弹出窗口，并且无边框

    // 设置按钮的悬停提示
    ui->tBtn_qianbi->setToolTip("铅笔");
    ui->tBtn_xiangpi->setToolTip("橡皮");
    ui->tBtn_wenben->setToolTip("文本框");
    ui->tBtn_tianchong->setToolTip("填充");

    // 设置按钮的点击不多选
    QList<QToolButton*> buttons = ui->widget->findChildren<QToolButton*>();
    for (QToolButton *button : buttons)
    {
        qDebug() << "Button name: " << button->objectName();
        QObject::connect(button, &QToolButton::clicked, [this, buttons, button]() {
            // 将其他按钮设置为未选中
            QString buttonName;
            QString sonMode;
            buttonName = button->objectName();  // 获取工具按钮的对象名
            ui->tBtn_qianbi;
            ui->tBtn_wenben;
            ui->tBtn_xiangpi;
            ui->tBtn_tianchong;
            if (buttonName == "tBtn_qianbi") {
                sonMode = "铅笔";
            } else if (buttonName == "tBtn_xiangpi") {
                sonMode = "橡皮";
            } else if (buttonName == "tBtn_wenben") {
                sonMode = "文本";
            } else if (buttonName == "tBtn_tianchong") {
                sonMode = "填充";
            }
            emit sonOfToolIsSelected(sonMode);
            for (QToolButton *otherButton : buttons)
            {
                if (otherButton != button)
                {
                    otherButton->setChecked(false);
                }
            }
        });
    }
}

ToolWidget::~ToolWidget()
{
    delete ui;
}

void ToolWidget::paintEvent(QPaintEvent *event)
{
    //绘制样式
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    painter.setRenderHint(QPainter::Antialiasing);
    //设置边框为圆角12px
    painter.drawRoundedRect(bmp.rect(), 12, 12);
    setMask(bmp);
    //再画颜色块
    QRect tmpRect = QRect(0, 0, this->width(), this->height());
    QBrush brush = QBrush(QColor("#ffffff"));
    p.setPen(Qt::NoPen);  //去掉边框线
    p.setBrush(brush);
    p.drawRect(tmpRect);

}

QList<QToolButton*> ToolWidget::getToolButtons()
{
    QList<QToolButton*> buttonList;
    // 查找 widget_4 下的所有 QToolButton
    QList<QToolButton*> allButtons = ui->widget->findChildren<QToolButton*>();
    // 将 QToolButton 添加到列表中
    for (QToolButton* button : allButtons) {
        buttonList.append(button);
    }
    qDebug() << "row 190, num of toollButton is " << buttonList.size();

    return buttonList;
}
